package com.olympus.hermes.product.service;

import com.olympus.hermes.common.service.AbstractService;
import com.olympus.hermes.common.support.PageRequest;
import com.olympus.hermes.product.bean.dto.product.CreateProductDTO;
import com.olympus.hermes.product.constants.PublishState;
import com.olympus.hermes.product.repo.ProductRepo;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Mickey
 * @since 2021/2/5
 */
@Service
@AllArgsConstructor
public class ProductService extends AbstractService {

    private final ProductRepo productRepo;

    public void create(CreateProductDTO createProduct) {
        creatorFor(productRepo)
                .instance(createProduct::convertTo)
                //设置新建的商品状态
                .update(product -> product.setPublishState(PublishState.NEW))
                .call();

    }

    public Page list(PageRequest pageRequest, Map<String, String> condition) {
        return productRepo.findAll((root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (condition.containsKey("name")) {
                predicates.add(builder.like(root.get("name"), "%" + condition.get("name") + "%"));
            }
            return builder.and(predicates.toArray(new Predicate[predicates.size()]));
        }, pageRequest);
    }

}
